Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
Match a line with a [ character, but don't match if it has a ] character

I thought this regex would match lines with a [, but not if it has a ]:

^.*\[.*(?!\]).*$

Instead, it's matching every line with a [ (shown in bold):

This [should match]. This line should match

This line shouldn't match.

This line shouldn't match. This line [shouldn't match.

How to fix that regex so that it doesn't match lines that have a ]?

This [should match]. This line should match

This line shouldn't match.

This line shouldn't match. This line [shouldn't match.

Demo: https://regexr.com/67qk7

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

This pattern ^.*\[.*(?!\]).*$ matches [ and the directly following .* will match the rest of the line.

Then at the end of the line it will assert not ] directly to the right, which is true because it already is at the end of the line. Then the .* is optional and it can assert the end of the string.

So it will match any whole line that has at least a single [

If you want to match pairs of opening till closing square brackets [...] and not allow any brackets inside it, or single brackets outside of it and matching at least a single pair, you can repeat 1 or more times matching pairs surrounded by optional chars other than square brackets.

^(?:[^\][\n]*\[[^\][\n]*\])+[^\][\n]*$

Regex demo

about 4 years ago · Juan Pablo Isaza Report

0

An alternate solution which is not super efficient but is a bit shorter:

^(?!.*\[[^\]\n]*$)[^[\n]*\[.+$

RegEx Demo

Explanation:

  • (?!.*\[[^\]\n]*$) fails the match if we get a [ without a closing ] anywhere
  • [^[\n]*\[ matches first [ in a line
about 4 years ago · Juan Pablo Isaza Report

0

"This regex would match lines with a [" (one or more), "but not if it has a ]" (one or more):

^[^\][\n]*\[[^\]\n]*$

Screenshot from Regex101

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!